package info.cs52.fes.action.user;

import info.cs52.fes.FesAction;
import info.cs52.fes.dao.UserDAO;
import info.cs52.fes.data.User;
import info.cs52.fes.prolog.Engine;
import info.cs52.fes.prolog.PrologException;
import info.cs52.fes.prolog.TuPrologEngine;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class KnowledgeBaseAction extends FesAction {

	public KnowledgeBaseAction() {
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			Long id = Long.parseLong(req.getParameter("id"));
			user = UserDAO.find(id);
		} catch (NumberFormatException e) {
			message = "ID không hợp lệ";
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (!"save".equals(req.getParameter("submit")) || !validate(req)) {
			return;
		}
		Long id = Long.parseLong(req.getParameter("id"));
		user = UserDAO.find(id);
		user.setKnowledgeBase(req.getParameter("kb"));
	}
	
	private boolean validate(HttpServletRequest req) {
		try {
			long id = Long.parseLong(req.getParameter("id"));
			if (UserDAO.find(id) == null) {
				message = "Không tìm thấy người dùng";
				return false;
			}
		} catch (NumberFormatException e) {
			message = "ID không hợp lệ";
			return false;
		}
		if (!StringUtils.isEmpty(req.getParameter("kb"))) {
			try {
				Engine engine = new TuPrologEngine();
				engine.setUserKnowledgeBase(req.getParameter("kb"));
			} catch (PrologException e) {
				message = "Cú pháp không hợp lệ";
				return false;
			}
		}
		return true;
	}

	private User user;

	public User getUser() {
		return user;
	}

}
